define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'report/stash_detail/index' + location.search,
                    add_url: 'report/stash_detail/add',
                    // edit_url: 'report/stash_detail/edit',
                    del_url: 'report/stash_detail/del',
                    multi_url: 'report/stash_detail/multi',
                    import_url: 'report/stash_detail/import',
                    table: 'stash_detail',
                }
            });

            var table = $("#table");

            table.on('post-common-search.bs.table', function (event, table) {
                var form = $("form", table.$commonsearch);

                $("input[name='unit_id']", form).addClass("selectpage").data("source", "basic/unit/index").data("primaryKey", "id").data("field", "name").data("orderBy", "id desc");

                $("input[name='stash_id']", form).addClass("selectpage").data("source", "basic/stash/index").data("primaryKey", "id").data("field", "name").data("orderBy", "id desc");

                $("input[name='staff_id']", form).addClass("selectpage").data("source", "basic/staff/index").data("primaryKey", "id").data("field", "name").data("orderBy", "id desc");

                $("input[name='assets_id']", form).addClass("selectpage").data("source", "basic/assets/index").data("primaryKey", "id").data("field", "name").data("orderBy", "id desc");

                Form.events.cxselect(form);
                Form.events.selectpage(form);
            });
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                searchFormVisible: true,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'), operate: false},
                        {field: 'order_no', title: __('Order_no'), operate: 'LIKE'},
                        {
                            field: 'date',
                            title: __('Date'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            autocomplete: false
                        },
                        {
                            field: 'status',
                            title: __('类型'),
                            searchList: {
                                "100": __('Status 100'),
                                "200": __('Status 200'),
                                "300": __('Status 300'),
                                "400": __('Status 400'),
                                "500": __('Status 500'),
                                "1300": __('调拨单'),
                                "1400": __('其他入库单'),
                                "1500": __('其他出库单'),
                            },
                            formatter: Table.api.formatter.status
                        },
                        //   {field: 'admin_id', title: __('Admin_id')},
                        {field: 'unit_id', title: __('单位')},
                        {field: 'stash_id', title: __('仓库')},
                        {field: 'assets_id', title: __('账户')},
                        {field: 'price', title: __('总金额'), operate: false},
                        {field: 'staff_id', title: __('Staff_id')},
                        {
                            field: 'remarks',
                            title: __('Remarks'),
                            operate: 'LIKE',
                            table: table,
                            class: 'autocontent',
                            formatter: Table.api.formatter.content
                        },

                        {
                            field: 'createtime',
                            title: __('Createtime'),
                            operate: false,
                            addclass: 'datetimerange',
                            autocomplete: false,
                            formatter: Table.api.formatter.datetime
                        },
                        //   {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {
                            field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate,
                            buttons: [
                                {
                                    name: 'detail',
                                    text: __('详情'),
                                    title: __('详情'),
                                    extend: 'data-area=["95%","95%"]',
                                    classname: 'btn btn-xs btn-primary btn-dialog',
                                    url: 'report/stash_detail/detail/order_no/{order_no}',
                                    callback: function (data) {
                                        Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                                    },
                                    visible: function (row) {
                                        //返回true时按钮显示,返回false隐藏
                                        return true;
                                    }
                                },
                                {
                                    name: 'detail',
                                    text: __('修改'),
                                    title: __('修改'),
                                    extend: 'data-area=["100%","100%"]',
                                    classname: 'btn btn-xs btn-primary btn-dialog',
                                    url: 'report/stash_detail/detail_edit/order_no/{order_no}',
                                    callback: function (data) {
                                        Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                                    },
                                    visible: function (row) {
                                        //返回true时按钮显示,返回false隐藏
                                        return true;
                                    }
                                },
                            ]
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'report/stash_detail/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '140px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'report/stash_detail/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'report/stash_detail/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },

        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        detail: function () {
            $(document).on("click", ".btn-dy", function (e) {
                window.print()
            })

            Controller.api.bindevent();
        },
        detail_edit: function (){
            $(document).on("click", ".goods_name", function (e) {
                var xh = (e.target.dataset.xh) * 1
                var url = 'basic/goods/select';
                var msg = '商品列表';
                var width = '1000px';
                var height = '600px';
                var area = [$(window).width() > 800 ? (width ? width : '800px') : '95%', $(window).height() > 600 ? (height ? height : '600px') : '95%'];
                var options = {
                    shadeClose: false,
                    shade: [0.3, '#393D49'],
                    area: area,
                    callback: function (value) {

                        //这个value就是传上来的值
                        $('.goods_id' + xh).val(value.id)
                        $('.goods_name' + xh).val(value.name)
                        $('.goods_number' + xh).val(value.number)
                        // if (value.jh_price) {
                        //     fz(xh, 1, value.jh_price.price)
                        // } else {
                        //     fz(xh, 1, value.retail_price)
                        //     fz(xh, 1, value.cost_price)
                        // }
                        fz(xh, 1, value.cost_price)
                        var num = xh += 1;
                        var html = getHtml(num);
                        if ($('.goods' + num).length <= 0) {
                            $('#goods').append(html)
                        }
                        getSumQty();
                        getSumAmount();
                    }
                };

                Fast.api.open(url, msg, options);

            })

            $(document).on("click", ".goods_del", function (e) {
                var xh = (e.target.dataset.xh) * 1
                if (xh != 1) {
                    $('.goods' + xh).remove();
                    getSumQty();
                    getSumAmount();
                }
            })

            $(document).on("keyup", ".goods_qty", function (e) {
                var xh = $(this).attr('data-xh')
                if ($('.goods_id' + xh).val()) {
                    var qty = $(this).val();
                    var price = $('.goods_price' + xh).val();
                    qty = parseFloat(qty)
                    price = parseFloat(price)
                    $('.goods_amount' + xh).val((qty * price).toFixed(2));
                    getSumQty();
                    getSumAmount();
                } else {
                    $(this).val('');
                }
            });
            $(document).on("keyup", ".goods_price", function (e) {
                var xh = $(this).attr('data-xh')
                if ($('.goods_id' + xh).val()) {
                    var price = $(this).val();
                    var qty = $('.goods_qty' + xh).val();
                    qty = parseFloat(qty)
                    price = parseFloat(price)
                    $('.goods_amount' + xh).val((qty * price).toFixed(2));
                    getSumQty();
                    getSumAmount();
                } else {
                    $(this).val('');
                }
            });

            $(document).on("keyup", ".goods_amount", function (e) {
                var xh = $(this).attr('data-xh')
                var amount = $(this).val();
                if ($('.goods_id' + xh).val() && amount) {

                    var qty = $('.goods_qty' + xh).val();
                    qty = parseFloat(qty)
                    amount = parseFloat(amount)
                    $('.goods_price' + xh).val((amount / qty).toFixed(2));
                    getSumQty();
                    getSumAmount();
                } else {
                    $(this).val('');
                }
            });

            Form.api.bindevent($("form[role=form]"), function () {
            }, function () {
            }, function (success, error) {
                layer.confirm('请仔细核对单据！避免出错。', {
                    btn: ['确定', '取消'] //按钮
                }, function (index) {
                    Form.api.submit($("form[role=form]"), function (data, ret) {
                        if(ret.code == 1){
                            setTimeout(function(){
                                location.reload()
                            },1000)
                        }
                    });
                    Layer.close(index);
                }, function () {
                });
                return false;

            });
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        },

    };

    function getHtml(num) {
        var html = '        <div class="form-group col-xs-12 goods' + num + '" style="margin-left: 5%">\n' +
            '            <label class="control-label col-xs-1 col-sm-1">' + num + '</label>\n' +
            '            <div class="col-xs-1 col-sm-1 cy-div">\n' +
            '                <input data-rule=""\n' +
            '                       class="form-control goods_number  goods_number' + num + '" data-xh="' + num + '"\n' +
            '                       name="goods_number[]" type="text" value="" readonly data-field="number" placeholder="商品编号">' +
            '  <input data-rule=""\n' +
            '                           class="form-control goods_id goods_id' + num + '" readonly data-xh="1"\n' +
            '                           name="goods_id[]" type="hidden" value="" data-field="number" placeholder="商品id">\n' +
            '            </div>\n' +
            '            <div class="col-xs-3 col-sm-3 cy-div">\n' +
            '                <input data-rule=""\n' +
            '                       class="form-control goods_name goods_name' + num + '" readonly name="goods_name[]" data-xh="' + num + '" type="text"\n' +
            '                         value="" placeholder="点击选择商品">\n' +
            '            </div>\n' +
            '            <div class="col-xs-1 col-sm-1 cy-div">\n' +
            '                <input data-rule=""\n' +
            '                       class="form-control goods_qty goods_qty' + num + '" name="goods_qty[]" type="text" value="" data-xh="' + num + '"\n' +
            '                       placeholder="数量">\n' +
            '            </div>\n' +
            '            <div class="col-xs-1 col-sm-1 cy-div">\n' +
            '                <input data-rule=""\n' +
            '                       class="form-control goods_price goods_price' + num + '" name="goods_price[]" type="text" value="" data-xh="' + num + '"\n' +
            '                       placeholder="单价">\n' +
            '            </div>\n' +
            '            <div class="col-xs-1 col-sm-1 cy-div">\n' +
            '                <input data-rule=""\n' +
            '                       class="form-control goods_amount goods_amount' + num + '" name="goods_amount[]" type="text" value="" data-xh="' + num + '"\n' +
            '                       placeholder="金额">\n' +
            '            </div>\n' +
            '            <div class="col-xs-2 col-sm-2 cy-div">\n' +
            '                <input data-rule=""\n' +
            '                       class="form-control goods_remarks goods_remarks' + num + '" name="goods_remarks[]" type="text" value="" data-xh="' + num + '"\n' +
            '                       placeholder="备注">\n' +
            '            </div>\n' +
            '   <div data-xh="' + num + '" class="col-xs-1 col-sm-1 cy-div goods_del" style="line-height: 35px;padding-left: 10px; cursor: pointer;">\n' +
            '                    删除\n' +
            '                </div>' +
            '        </div>'

        return html
    }
    function getSumQty() {
        var inputs = $('.goods_qty');
        var sum_qty = 0;
        inputs.each(function () {
            sum_qty = sum_qty + $(this).val() * 1;
        });
        $('#sum_qty').text(sum_qty);
    }

    function getSumAmount() {
        var inputs = $('.goods_amount');
        var sum_amount = 0;
        inputs.each(function () {
            sum_amount = sum_amount + $(this).val() * 1;
        });
        $('#sum_amount').text(sum_amount.toFixed(2));
    }

    function fz(xh, qty, price) {
        $('.goods_qty' + xh).val(qty);
        $('.goods_price' + xh).val(price);
        qty = parseFloat(qty)
        price = parseFloat(price)
        $('.goods_amount' + xh).val((qty * price).toFixed(2));
    }
    return Controller;
});
